/**
 * Copyright (c) 2007, Nathan A. Good
 *
 *	All rights reserved.
 *
 *	Redistribution and use in source and binary forms, with or without 
 *	modification, are permitted provided that the following conditions are met:
 *
 *	*	Redistributions of source code must retain the above copyright notice, 
 *		this list of conditions and the following disclaimer.
 *
 *	*	Redistributions in binary form must reproduce the above copyright 
 *		notice, this list of conditions and the following disclaimer in the 
 *		documentation and/or other materials provided with the distribution.
 *
 *	*	Neither the name of the Crown Financial Ministries nor the names of 
 *		its contributors may be used to endorse or promote products derived
 *		from this software without specific prior written permission.
 *
 *	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 *	AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
 *	IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
 *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
 *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
 *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
 *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
 *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
 *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
 *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 
 *  THE POSSIBILITY OF SUCH DAMAGE.
 */
package org.crown.kings.jsf;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.crown.kings.dao.AddressEntityDAO;
import org.crown.kings.dao.AddressEntityDAOImpl;
import org.crown.kings.dao.DBMapper;
import org.crown.kings.entities.AddressEntity;
import org.crown.kings.entities.AddressEntityExample;
import org.crown.kings.jsf.formatters.BeanFormatter;
import org.crown.kings.jsf.formatters.BeanFormatterFactory;

public class AddressBean extends BaseAddressBean
{

	private final static Log logger = LogFactory.getLog(AddressBean.class);

	/**
	 * 
	 * @param id
	 * @return
	 */
	public static List<AddressBean> getAddressesFor(int id)
	{
		List<AddressBean> results = new ArrayList<AddressBean>();
		AddressEntityDAO dao = new AddressEntityDAOImpl(DBMapper.instance().getSqlMapper());
		AddressEntityExample example = new AddressEntityExample();
		example.createCriteria().andPersonIdEqualTo(id);

		try {
			List<AddressEntity> entities = dao.selectByExample(example);

			if (logger.isDebugEnabled()) {
				logger.debug("Got " + ((entities != null) ? entities.size() : "0") + " entities.");
			}

			for (AddressEntity entity : entities) {
				results.add((AddressBean) new AddressBeanAdapter(entity));
			}

		} catch (SQLException e) {
			logger.error("Database error while getting addresses", e);
		}
		return results;
	}
	private String city;
	private String extendedAddress;
	private String postalCode;

	private String state;

	/**
	 * Adds the current AddressBean to the persistent store.
	 * 
	 * @return String Result of the add operation.
	 */
	public String doAdd()
	{
		String result = ActionResults.FAILURE;

		PersonWipBean wip = getPersonWip();

		if (wip == null) {
			/*
			 * Uh, oh. We're in an invalid state, because if we're adding an
			 * address we have to know the person WIP.
			 */
		} else {
			AddressEntityDAO dao = new AddressEntityDAOImpl(DBMapper.instance().getSqlMapper());
			AddressEntityAdapter entity = new AddressEntityAdapter(this);
			entity.setPersonId(wip.getId());
			try {
				dao.insert((AddressEntity) entity);
			} catch (SQLException e) {
				logger.error("Error occurred while inserting address:", e);
			}
		}

		result = ActionResults.SUCCESS;
		return result;
	}

	/**
	 * Removes the given address.
	 * @return
	 */
	public String doRemove()
	{
		String result = ActionResults.FAILURE;

		result = ActionResults.SUCCESS;
		return result;

	}

	public String getCity()
	{
		return city;
	}

	/**
	 * Gets the proper display text for this bean when it is printed to a single String.
	 * @return
	 */
	public String getDisplayText()
	{
		return BeanFormatterFactory.instance().createBeanFormatter(AddressBean.class).format(this);
	}

	public String getExtendedAddress()
	{
		return extendedAddress;
	}

	/**
	 * Returns a list of addresses for the given user.
	 * 
	 * @return List of address beans
	 */
	public List<AddressBean> getList()
	{
		List<AddressBean> results = new ArrayList<AddressBean>();
		try {
			PersonWipBean wip = (PersonWipBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("personWip");

			if (wip == null) {
				addMessage(FacesMessage.SEVERITY_ERROR, "No ID of a working entity was found in session.");
			} else {
				results = AddressBean.getAddressesFor(wip.getId());
			}
		} catch (Throwable t) {
			handle(t, "Error getting list of addresses");
		}

		return results;
	}
	
	

	public String getPostalCode()
	{
		return postalCode;
	}

	public String getState()
	{
		return state;
	}

	public void setCity(final String city)
	{
		this.city = city;
	}

	public void setExtendedAddress(final String extendedAddress)
	{
		this.extendedAddress = extendedAddress;
	}
	
	public void setPostalCode(final String postalCode)
	{
		this.postalCode = postalCode;
	}

	public void setState(final String state)
	{
		this.state = state;
	}
	
	@Override
	public String toString()
	{
		BeanFormatter formatter = BeanFormatterFactory.instance().createBeanFormatter(this.getClass());
		return formatter.format(this);
	}

}
